print("读取CSV文件")
print("读取CSV文件，包含文件头")
import csv
with open(file="./files/csv001.csv",mode="r",encoding="utf-8") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

print("读取CSV文件，不包含文件头")
with open(file="./files/csv001.csv",mode="r",encoding="utf-8") as file:
    reader = csv.reader(file)
    next(reader)
    for row in reader:
        print(row)

print("读取CSV文件，并将每一行元素和表头结合，封装成字典")
with open("./files/csv001.csv",mode="r",encoding="utf-8") as file:
    reader = csv.reader(file)
    header = next(reader)
    for row in reader:
        print(dict(zip(header,row)))

print("读取CSV文件，读取出来即为字典")
with open(file="./files/csv001.csv",mode="r",encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)

print("写入CSV文件")
print("将二维数组写入CSV文件，其中每一个数组元素是一行")
data=[["name","age"],["zhangsan",30],["lisi",31],["wangwu",26],["zhaoliu",27]]
with open(file="./files/csv002.csv",mode="w",encoding="utf-8",newline="\n") as file:
    writer = csv.writer(file)
    writer.writerows(data)

print("将一维数据写入CSV文件")
data2=["田七",33]
with open(file="./files/csv003.csv",mode="a",encoding="utf-8",newline="\n") as file:
    writer = csv.writer(file)
    writer.writerow(data2)
    writer.writerow(data)

print("字典的列表数据写入CSV文件")
import csv
data = [
    {'name': 'Alice', 'age': [30,20], 'city': 'New York'},
    {'name': 'Bob', 'age': [25,28], 'city': 'Los Angeles'},
    {'name': 'Charlie', 'age': [35,33], 'city': 'Chicago'}
]
with open(file="./files/csv004.csv",mode="w",encoding="utf-8") as file:
    fields=list(data[0].keys())
    writer = csv.DictWriter(f=file,fieldnames=fields)
    writer.writeheader()
    for d in data:
        writer.writerow(d)


print("写入txt文件")
with open(file="./files/txt001.txt",mode="w",encoding="utf-8") as file:
    for s in "hello world".split():
        file.write(s+"\n")

print("读取txt文件")
with open(file="./files/txt001.txt",mode="r",encoding="utf-8") as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())

print("读取json文件")
import json
with open(file="./files/json001.json",mode="r",encoding="utf-8") as file:
    data=json.load(file)
    print(type(data))
    print(data)

print("写入JSON文件")
import json
with open(file="./files/json002.json",mode="w",encoding="utf-8") as file:
    json.dump(data,fp=file,ensure_ascii=False)